package net.freebytes.es.common.auto;

import net.freebytes.es.common.annotation.EnableESTools;
import net.freebytes.es.common.util.ScanSupport;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.Map;
import java.util.Set;

@Component
public class RegisterProcessor implements BeanFactoryPostProcessor, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        EnableESTools enableESTools = getEnableESTools();
        String[] entityPaths = enableESTools.entityPath();
        try {
            for (String path : entityPaths) {
                Set<Class<?>> classes = new ScanSupport().doScan(path);
                for (Class<?> a : classes) {
                    beanFactory.registerSingleton(a.getSimpleName(), a.newInstance());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    protected EnableESTools getEnableESTools() {
        String[] beanNames = applicationContext.getBeanNamesForAnnotation(EnableESTools.class);
        String beanName = beanNames[0];
        Object bean = applicationContext.getBean(beanName);
        Class<?> aClass = bean.getClass();
        EnableESTools annotation = aClass.getAnnotation(EnableESTools.class);
        return annotation;
    }

    protected Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) {
        return this.applicationContext.getBeansWithAnnotation(annotationType);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}